﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Mine
{
    class Track
    {
        static private Random Srand = new Random();
        private Random rand;
        private double consumption;
        private int MaxStone;
        private IStation Source, Destination;
        private static DateTime endTime;//szalbiztos
        private static object endTimeLock=new object();
        private static int NumberOfUnsimulatedTracks = 0;
        private static System.Threading.ManualResetEvent isFinished = new System.Threading.ManualResetEvent(false);

        public static System.Threading.ManualResetEvent IsFinished
        {
            get { return Track.isFinished; }
        }
        private static void EndOfSimulation()
        {
            lock (endTimeLock)
            {
                NumberOfUnsimulatedTracks--;
                if (NumberOfUnsimulatedTracks == 0)
                {
                    isFinished.Set();
                    endTime = DateTime.Now;
                }
            }
        }

        public static DateTime EndTime
        {
            get { return Track.endTime; }
            set { Track.endTime = value; }
        }
        public int IDa
        {
            get
            {
                return Source.ID;
            }
        }
        public int IDb
        {
            get
            {
                return Destination.ID;
            }
        }

        public Track(IStation source, IStation destination, int maxstone)
        {
            NumberOfUnsimulatedTracks++;
            consumption = 0;
            Source = source;
            Destination = destination;
            MaxStone = maxstone;
            rand = new Random(Srand.Next());
        }

        public Simulator Simulation
        {
            get
            {
                return new Simulator(Simulate);
            }
        }

        private void Simulate(object Mo)
        {
            int M = (int)Mo;
            for (int i = 0; i < M; i++)
            {
                IStation a, b;//a bol b be szallitunk
                if (rand.Next(2) == 0)//ki valaszjuk az iranyt
                {
                    a = Source;
                    b = Destination;
                }
                else
                {
                    b = Source;
                    a = Destination;
                }
                int t = rand.Next(MaxStone) + 1;
                consumption += a.MoveStones(t, b);//kiveszunk t kovet
            }

            EndOfSimulation();
        }

        public double Consuption
        {
            get
            {
                return consumption;
            }
        }
    }
}
